import React from 'react';
import { Toast, Form, Input, Button, Radio, Dropdown, TextArea } from 'antd-mobile';
import './contactadd.scss';
import cookie from 'react-cookies';
import { pcaa } from 'area-data';
import 'react-area-linkage/dist/index.css';
import { AreaCascader } from 'react-area-linkage';
import { useNavigate, useSearchParams } from 'react-router-dom';

const Contact = () => {

    let navigate = useNavigate()
    let [searchParams] = useSearchParams()
    const ref = React.useRef()
    const LoginUser = cookie.load('LoginUser') ? cookie.load('LoginUser') : ''
    const [region, setregion] = React.useState([])
    const [typelist, settypelist] = React.useState([])
    const [typetitle, settypetitle] = React.useState('请选择')
    const [typeid, settypeid] = React.useState('1')
    const typeids = searchParams.get('typeids')  // 路由传值
    const [form] = Form.useForm()
    // console.log(LoginUser)

    let isMount = false

    React.useEffect(() => {
        async function typeData () {
            let result = await React.$api.contacttype()
            if (result.code == '1' && !isMount) {
                settypelist(result.data)
            }
        }
        typeData()

        async function info () {
            if (typeids) {
                let result = await React.$api.contactinfo({ id: typeids, userid: LoginUser.id })
                if (result.code == '1' && !isMount) {
                    let data = result.data
                    settypeid(data.typeid)
                    settypetitle(data.type.name)
                    setregion(data.region.split(','))
                    // 动态改变表单值
                    form.setFieldsValue(data)
                }
            } else {
                let data = {
                    nickname: '',
                    phone: '',
                    typeid: '',
                    gender: '0',
                    region: [],
                    remark: ''
                }
                settypeid('1')
                settypetitle('请选择')
                form.setFieldsValue(data)
            }
        }
        info()

        return () => isMount = true
    }, [typeids])

    const contactAdd = async (value) => {
        console.log(value)
        let data = {
            userid: LoginUser.id,
            typeid: typeid,
            nickname: value.nickname,
            phone: value.phone,
            gender: value.gender ? value.gender : '0',
            region: region,
            remark: value.remark
        }
        let result = {}
        if (typeids) {
            data.id = typeids
            result = await React.$api.contactupdate(data)
        } else {
            result = await React.$api.contactadd(data)
        }
        if (result.code == '1') {
            Toast.show({
                icon: 'success',
                content: result.msg,
            })
            navigate('/')
        } else {
            Toast.show({
                icon: 'fail',
                content: result.msg,
            })
            return false
        }
        // console.log(value)
    }

    const selectedChange = (e) => {
        let [province, city, district] = e
        let region = []
        if (province) {
            region.push(Object.keys(province)[0])
        }
        if (city) {
            region.push(Object.keys(city)[0])
        }
        if (district) {
            region.push(Object.keys(district)[0])
        }
        setregion(region)
        // console.log(e)
    }

    const changeType = (e) => {
        console.log(e)
        settypetitle(e.name)
        settypeid(e.id)
        // 关闭下拉菜单
        ref.current?.close()
    }

    return (
        <>
            {/* 信息录入 */}
            <div className='contacts'>
                <div className='info'>
                    <h3 className='title wow fadeInUp'>信息录入</h3>

                    <p className='desc wow fadeInUp' data-wow-delay='200ms'>
                        您可在本页录入联系信息，录入成功后名片将会出现在首页。如需修改首页名片信息，也请新建录入，将会自动替换原有名片。
                    </p>
                </div>
            </div>

            <Form onFinish={contactAdd} layout='horizontal' form={form}>

                <Form.Item
                    name='nickname'
                    label='姓名'
                    rules={[{ required: true, message: '姓名不能为空' }]}
                >
                    <Input placeholder='请输入姓名' />
                </Form.Item>

                <Form.Item
                    name='phone'
                    label='手机'
                    rules={[{ required: true, message: '手机号不能为空' }]}
                >
                    <Input placeholder='请输入手机号' />
                </Form.Item>

                <Form.Item
                    name='gender'
                    label='性别'
                >
                    <Radio.Group defaultValue='0'>
                        <Radio value='0'>保密</Radio>
                        <Radio value='1'>男</Radio>
                        <Radio value='2'>女</Radio>
                    </Radio.Group>
                </Form.Item>

                <Form.Item
                    name='region'
                    label='地区'
                >
                    <AreaCascader type='all' defaultValue={region} onChange={selectedChange} level={1} data={pcaa} />
                </Form.Item>

                <Form.Item
                    name='typeid'
                    label='分类'
                >
                    <Dropdown ref={ref}>
                        <Dropdown.Item key='sorter' title={typetitle}>
                            <div style={{ padding: 12 }} className="contacttype">
                                <Radio.Group defaultValue='default' onChange={changeType}>
                                    {
                                        typelist.map((item, index) => {
                                            return (
                                                <Radio block value={item} key={index}>
                                                    {item.name}
                                                </Radio>
                                            )
                                        })
                                    }
                                </Radio.Group>
                            </div>
                        </Dropdown.Item>
                    </Dropdown>
                </Form.Item>

                <Form.Item
                    name='remark'
                    label='备注'
                >
                    <TextArea
                        showCount
                        maxLength={100}
                    />
                </Form.Item>

                <div className='action'>
                    <Button block type='submit' color='primary' size='large'>
                        {typeids ? '编辑' : '新建'}
                    </Button>
                </div>

            </Form>
        </>
    )
}

export default Contact;